import os
from pyltp import Segmentor, Postagger
from utils.wrapData import (
    wrapLtpItem
)
# 把相对路径改成绝对路径
CURRENT_PATH = os.path.abspath(__file__)
LTP_DATA_DIR = os.path.abspath(os.path.join(CURRENT_PATH, '..', '..', '..', 'model_file', 'ltp_data_v3.4.0'))

# 分词
def cutSentenceToWords(sentence):
    # 分词模型路径，模型名称为`cws.model`
    cws_model_path = os.path.join(LTP_DATA_DIR, 'cws.model')
    segmentor = Segmentor(cws_model_path)
    # 分词
    words = segmentor.segment(sentence)
    return words

# 词性标注
def posTagging(words):
    pos_model_path = os.path.join(LTP_DATA_DIR, 'pos.model')  # 词性标注模型路径，模型名称为`pos.model`
    postagger = Postagger(pos_model_path)  # 初始化实例
    postags = postagger.postag(words)  # 词性标注
    return postags

# 获取最终的结果
"""
数据格式：
[
    {
       "word": "xxx",
       "tag": "xx" 
    },
    ...
]
"""
def getResultFromSentence(sentence):
    result = []
    words = cutSentenceToWords(sentence)
    tags = posTagging(words)
    for i in range(len(words)):
        tempObj = wrapLtpItem(word = words[i], tag = tags[i])
        result.append(tempObj)
    return result
